/**
 * Created by wenhui on 2017/2/9.
 */
angular.module('login.controller',[])
  .controller('loginCtrl',['$scope','$state','loginService','$localstorage','$ionicPopup','$cordovaAppVersion','$ionicLoading', '$cordovaFileTransfer', '$cordovaFileOpener2', '$timeout','$http','$window',function($scope,$state,loginService,$localstorage,$ionicPopup,$cordovaAppVersion, $ionicLoading, $cordovaFileTransfer, $cordovaFileOpener2, $timeout,$http,$window){

    $scope.$on('$ionicView.enter', function (event, data) {
      $scope.loginData=loginService.getLoginData();
      $scope.params=loginService.getParams();// 必须放第一位  否则有问题
      $scope.params.upstate="已更新";
      $scope.yanzheng=true;
      $scope.hqyzm="获取验证码";
      $scope.loginData.randomNum="";
      $scope.version="1.0.2";
      if(!$localstorage.get("chkrempwd")||$localstorage.get("chkrempwd")=="no"){
        $scope.loginData.chkrempwd="no";
        $scope.loginData.password="";
        $scope.loginData.staffId=$localstorage.get("staffId");//记住用户名
      }else {
        $scope.loginData.chkrempwd = "yes";
        $scope.loginData.password = $localstorage.get("password");
        $scope.loginData.staffId = $localstorage.get("staffId")
      }
    });



    document.addEventListener('deviceready', function () {
      checkUpdate();
    });
    //检查版本
    function checkUpdate()
    {
        console.log("检验APP版本：checkUpdate");
      loginService.doQueryLatestVersion().then(function(data){
        if(data.respCode=="0")
        {
            console.log("-------------------zipver:"+data.data.VERSION);
          $scope.params.zipver=data.data.VERSION;
          $scope.params.downloadframeworkpath=data.data.FILEPATH;
            if ($scope.version != $scope.params.zipver && data.data.UPDATE_FLAG =="1") {
              showUpdateConfirm();
            }
        }
        else {
          var alertPopup = $ionicPopup.alert({
            title: '获取版本信息',
            template: data.respDesc, //从服务端获取更新的内容
            okText: '确定',
            okType:'item-customer-bg-darkred'
          });
        }
      },function(error){
        var alertPopup = $ionicPopup.alert({
          title: '获取版本信息',
          template: '获取版本信息异常，请联系管理员', //从服务端获取更新的内容
          okText: '确定',
          okType:'item-customer-bg-darkred'
        });
      });
    }
    //显示是否更新对话框
    function showUpdateConfirm()
    {
      var confirmPopup = $ionicPopup.confirm({
        title: '版本升级',
        template: '发现新版本，确定升级吗', //从服务端获取更新的内容
        cancelText: '取消',
        cancelType:'item-customer-bg-lightred',
        okText: '升级',
        okType:'item-customer-bg-darkred'
      });
      confirmPopup.then(function (res) {
        if (res) {
          $ionicLoading.show({
            template: "有新版，已经下载：0%"
          });
          //正式服
          var url = $scope.params.downloadframeworkpath;
          //测试服
          var targetPath = cordova.file.externalDataDirectory + "OutCallApp.apk";
          var trustHosts = true
          var options = {};
         $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
                     .then(function (result) {
                           console.log("-------------------targetPath:"+targetPath);
                           $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
                           ).then(function () {
                             // 成功
                             //alert("成功！");
                           }, function (err) {
                             // 错误
                             //alert("失败");
                           });
                     }, function (err) {
                       var alertPopup = $ionicPopup.alert({
                         title: '下载文件失败',
                         template: '下载失败', //从服务端获取更新的内容
                         okText: '确定',
                         okType:'item-customer-bg-darkred'
                       });
                     }, function (progress) {
                       //进度，这里使用文字显示下载百分比
                       $timeout(function () {
                         var downloadProgress = (progress.loaded / progress.total) * 100;
                         $ionicLoading.show({
                           template: "有新版，已经下载：" + Math.floor(downloadProgress) + "%"
                         });
                         if (downloadProgress > 99) {
                           $ionicLoading.hide();
                           // $scope.getLocation();
                         }
                       })
                     });

        } else {
          //取消更新
          //ionic.Platform.exitApp();
        }
      })
    }


    //获取短信验证码
    $scope.doGenerateSmsVerifyCode=function()
    {
        console.log("获取短信验证码");
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds(); 
        $scope.loginData.Loing_Key = year + '.' + month + '.' + day + '.' + hour + '.' + minute + '.' + second;
        console.log("Loing_Key:"+$scope.loginData.Loing_Key);
      if($scope.yanzheng){
        loginService.doGenerateSmsVerifyCode().then(function(data){

          if(data.success==true)
          {
            $scope.enWrite=false;//可用
            $scope.time=60;
            var jsyzm=null;
            var updateClock = function(i) {
              $scope.hqyzm="重新获取("+$scope.time--+")";
              if($scope.time==1){
                $scope.hqyzm="获取验证码";
                clearInterval(jsyzm);
                $scope.yanzheng=true;
              }
            };
            jsyzm=setInterval(function() {
              $scope.$apply(updateClock());
            }, 1000);
            $scope.yanzheng=false;
          }
          else
          {
            var alertPopup=$ionicPopup.alert({
              title:"获取短信验证码失败",
              template:data.msg,
              okText: '确定', // String (默认: 'OK')。OK按钮的文字。
              okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
            });
          }
        },function(error){
          var alertPopup=$ionicPopup.alert({
            title:'获取短信验证码失败',
            template:"异常错误",
            okText: '确定', // String (默认: 'OK')。OK按钮的文字。
            okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
          });
        });
      }
    }


    function getLocation(){
      var lat="";
      var lng="";
      var posOptions = {timeout: 10000, enableHighAccuracy: false};
      $cordovaGeolocation
        .getCurrentPosition(posOptions)
        .then(function (position) {
          console.log(position);
          lat=position.coords.latitude;
          lng=position.coords.longitude;
          var param={
            "lat":lat,
            "lng":lng
          }
          console.log(lat+","+lng);
        }, function(err) {
          var alertPopup = $ionicPopup.alert({
            title: '请打开手机GPS功能',
            template: '请确认您的GPS定位功能已经打开且正常连接网络，点击确认退出', //从服务端获取更新的内容
            cancelType:'item-customer-bg-lightred',
            okText: '确定',
            okType:'item-customer-bg-darkred'
          });
          alertPopup.then(function(result){
            ionic.Platform.exitApp();
          });
        });

    }




    //验证码校验
       $scope.doVerifySmsVerifyCode=function()
     {
     loginService.doGerifySmsVerifyCode().then(function(data){

     if(data.respCode=="0")
     {
     //$scope.enLoging=false;
     $scope.doLogin();
     }
     else
     {
     var alertPopup=$ionicPopup.alert({
     title:"短信验证码校验失败",
     template:"短信验证码校验失败,"+data.msg,
     okText: '确定', // String (默认: 'OK')。OK按钮的文字。
     okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
     });
     }
     },function(error){
     var alertPopup=$ionicPopup.alert({
     title:'获取短信验证码失败',
     template:"异常错误",
     okText: '确定', // String (默认: 'OK')。OK按钮的文字。
     okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
     });
     });
     }

    $scope.doimg=function(){
      if($localstorage.get("chkrempwd")=="no"){
        $localstorage.set("chkrempwd","yes");
        $scope.loginData.chkrempwd="yes"
      }else{
        $localstorage.set("chkrempwd","no");
        $scope.loginData.chkrempwd="no"
      }
    }
 

    $scope.custAlert=function(title,template)
    {
      var alertPopup=$ionicPopup.alert({
        title:title,
        template:template,
        okText: '确定', // String (默认: 'OK')。OK按钮的文字。
        okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
      });
    }


    //点击登录
    $scope.doLogin=function() {
        $localstorage.set("Depart_Code", '1509091132486370');
        $localstorage.set("User_ID", '1802111748318674');
        $localstorage.set("Phone", '15599111788');
        $state.go('tab.maincontent'); return;


        var errmsg = "";
      if ($scope.loginData.randomNum == "") {
          errmsg= "请输入验证码!" ; 
      }
      if ($scope.loginData.staffId == "") {
          errmsg= "请输入电话或用户名!" ;
      }
      if ($scope.loginData.Loing_Key == "") {
          errmsg = "请先获取验证码!";
      }


      if (errmsg != "") {
          var alertPopup = $ionicPopup.alert({
              title: '登录失败',
              template: errmsg,
              okText: '确定', // String (默认: 'OK')。OK按钮的文字。
              okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
          });
      } else {
        var param = {
          "staffId": $scope.loginData.staffId,
          "password": $scope.loginData.password,
          "randomNum": $scope.loginData.randomNum,
          "Loing_Key": $scope.loginData.Loing_Key
        }
        loginService.doLogin(param).then(
          function (data) {
            if (data.success  ) {
                $localstorage.set("Depart_Code", data.Depart_Code);
              $localstorage.set("User_ID", data.User_ID);
              $localstorage.set("Phone", data.Phone); 
              if ($scope.loginData.chkrempwd == "yes")//记住密码
              {
                $localstorage.set("staffId", $scope.loginData.staffId);
                $localstorage.set("password", $scope.loginData.password);
              }
              else {
                $localstorage.set("staffId", $scope.loginData.staffId);
                $localstorage.set("password", "");
              }
              $state.go('tab.maincontent');

            }
            else {
              // $localstorage.set("staffId",$scope.loginData.staffId);
              var alertPopup = $ionicPopup.alert({
                title: "登录失败",
                template: data.msg,
                okText: '确定', // String (默认: 'OK')。OK按钮的文字。
                okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
              });
            }
          }, function (error) {
            var alertPopup = $ionicPopup.alert({
              title: '登录失败',
              template: "异常错误，链接不到服务器",
              okText: '确定', // String (默认: 'OK')。OK按钮的文字。
              okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
            });
          });
      }
    }

  }]);
